#!/usr/bin/env python3
# coding=utf-8
"""
Python 3.14 多线程性能测试 - 混合任务
测试CPU密集型和I/O密集型混合任务的多线程性能
"""

import threading
import time
import random
import concurrent.futures
from typing import List, Tuple


def mixed_task(task_id: int, cpu_ratio: float = 0.5) -> Tuple[int, float]:
    """
    混合任务：CPU计算 + 模拟I/O等待
    
    参数:
        task_id (int): 任务ID
        cpu_ratio (float): CPU密集型任务比例
    
    返回:
        Tuple[int, float]: (任务ID, 执行时间)
    """
    start_time = time.time()
    
    # CPU密集型部分
    cpu_iterations = int(1000000 * cpu_ratio)
    result = 0
    for i in range(cpu_iterations):
        result += i * random.random()
    
    # I/O密集型部分（模拟）
    io_time = 0.1 * (1 - cpu_ratio)  # 模拟I/O等待时间
    time.sleep(io_time)
    
    end_time = time.time()
    execution_time = end_time - start_time
    
    return task_id, execution_time


def single_thread_mixed_test(num_tasks: int, cpu_ratio: float) -> float:
    """单线程混合任务测试"""
    start_time = time.time()
    
    results = []
    for i in range(num_tasks):
        task_id, exec_time = mixed_task(i, cpu_ratio)
        results.append((task_id, exec_time))
    
    end_time = time.time()
    total_time = end_time - start_time
    
    print(f"单线程混合任务({num_tasks}个任务)耗时: {total_time:.4f} 秒")
    print(f"平均任务执行时间: {sum(t[1] for t in results) / len(results):.4f} 秒")
    
    return total_time


def multi_thread_mixed_test(num_threads: int, num_tasks: int, cpu_ratio: float) -> float:
    """多线程混合任务测试"""
    start_time = time.time()
    
    threads = []
    results = []
    
    def worker(task_id):
        task_id, exec_time = mixed_task(task_id, cpu_ratio)
        results.append((task_id, exec_time))
    
    for i in range(num_tasks):
        thread = threading.Thread(target=worker, args=(i,))
        threads.append(thread)
        thread.start()
    
    for thread in threads:
        thread.join()
    
    end_time = time.time()
    total_time = end_time - start_time
    
    print(f"{num_threads}线程混合任务({num_tasks}个任务)耗时: {total_time:.4f} 秒")
    print(f"平均任务执行时间: {sum(t[1] for t in results) / len(results):.4f} 秒")
    
    return total_time


def thread_pool_mixed_test(num_threads: int, num_tasks: int, cpu_ratio: float) -> float:
    """线程池混合任务测试"""
    start_time = time.time()
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
        futures = [
            executor.submit(mixed_task, i, cpu_ratio) 
            for i in range(num_tasks)
        ]
        results = [future.result() for future in futures]
    
    end_time = time.time()
    total_time = end_time - start_time
    
    print(f"线程池混合任务({num_threads}线程, {num_tasks}个任务)耗时: {total_time:.4f} 秒")
    print(f"平均任务执行时间: {sum(t[1] for t in results) / len(results):.4f} 秒")
    
    return total_time


def mixed_performance_test():
    """混合任务性能测试"""
    print("=== Python 3.14 混合任务多线程性能测试 ===")
    
    # 测试参数
    num_threads = 4
    num_tasks = 8
    cpu_ratios = [0.2, 0.5, 0.8]  # 不同的CPU/I/O比例
    
    for cpu_ratio in cpu_ratios:
        print(f"\n--- CPU比例: {cpu_ratio:.1f}, I/O比例: {1-cpu_ratio:.1f} ---")
        
        # 单线程测试
        print("1. 单线程测试:")
        single_time = single_thread_mixed_test(num_tasks, cpu_ratio)
        
        # 多线程测试
        print("\n2. 多线程测试:")
        multi_time = multi_thread_mixed_test(num_threads, num_tasks, cpu_ratio)
        
        # 线程池测试
        print("\n3. 线程池测试:")
        pool_time = thread_pool_mixed_test(num_threads, num_tasks, cpu_ratio)
        
        # 性能分析
        print(f"\n性能提升:")
        print(f"  多线程加速比: {single_time / multi_time:.2f}x")
        print(f"  线程池加速比: {single_time / pool_time:.2f}x")
        
        if multi_time < single_time:
            print("  ✅ 多线程性能提升！")
        else:
            print("  ⚠️  多线程性能未提升")


if __name__ == "__main__":
    mixed_performance_test()